package com.jsz.peini.server.thread;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.log4j.Logger;

import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.bean.user.UserInfoExample;
import com.jsz.peini.common.util.SpringContextUtil;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.redis.base.RedisConstants;
import com.jsz.peini.redis.base.RedisUtil;
import com.jsz.peini.redis.util.UserRedisUtil;
import com.jsz.peini.service.user.UserInfoService;
import com.jsz.peini.vo.UserVo;


public class BuyRankThread extends Thread{
	
	Logger logger = Logger.getLogger(BuyRankThread.class);
	
	public void init(){
		this.start();
	}
	
	@Override
	public void run() {
		super.run();
		
		UserInfoMapper userInfoMapper = (UserInfoMapper)SpringContextUtil.getBean(UserInfoMapper.class);
		UserInfoService userInfoService = (UserInfoService)SpringContextUtil.getBean(UserInfoService.class);
		
		while(true)
		{
			try {
				List<byte[]> list = RedisUtil.brpop(RedisConstants.BUY_RANK.getBytes());
				if(list.size() > 1){
					UserInfoExample userExample = new UserInfoExample();
					userExample.createCriteria().andBuyListGreaterThan(0);
					List<UserInfo> useList = userInfoMapper.selectByExample(userExample);
					
					List<LinkedHashMap<String,Object>> rankList = userInfoService.getRank(1, 2);
					
					for (UserInfo userInfo : useList) {
						userInfo.setBuyList(0);
						userInfoMapper.updateByPrimaryKey(userInfo);
						
						//更新缓存
						UserVo userVo = UserRedisUtil.getUserVoByUserId(userInfo.getId());
						userVo.setBuyList(new BigDecimal(0));
						UserRedisUtil.addUserToRedis(userVo);
					}
					for (int i = 0; i < rankList.size(); i++) {
						LinkedHashMap<String,Object> rank = rankList.get(i);
						UserInfo uInfo = new UserInfo();
						uInfo.setId(rank.get("userId").toString());
						uInfo.setBuyList(i+1);
						userInfoMapper.updateByPrimaryKeySelective(uInfo);
						
						//更新缓存
						UserVo userVo = UserRedisUtil.getUserVoByUserId(rank.get("userId").toString());
						userVo.setBuyList(new BigDecimal(i+1));
						UserRedisUtil.addUserToRedis(userVo);
					}
				}
				
				Thread.sleep(1);
			} catch (Exception e1) {
				e1.printStackTrace();
				logger.info("fail", e1);
			}
		}
		
	}
	
}